// // 选择国家
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';
import 'package:ones/values/colors.dart';
import 'package:provider/provider.dart';

import '../../lib_basemodel/country/country_model.dart';
import '../../lib_baseview/lib_baseview.dart';
import '../../lib_baseview/theme/jr.dart';
import '../../lib_baseview/utils/constant/app_colors.dart';
import '../../lib_baseview/widget/appbar/custom_app_bar.dart';
import '../../lib_runtime/extension/string_extension/string_text.dart';
import '../../resource/language/generated/l10n.dart';
import 'select_country_model.dart';

class SelectCountryPage extends StatefulWidget {
  final Function(CountryModel?)? onCountrySelected;
  const SelectCountryPage({super.key, this.onCountrySelected});

  @override
  State<StatefulWidget> createState() => _SelectCountryPageState();
}

class _SelectCountryPageState extends State<SelectCountryPage> {
  final TextEditingController _searchController = TextEditingController();
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    _searchController.addListener(() {
      setState(() {
        _searchQuery = _searchController.text;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => SelectCountryModel(),
      child: Container(
        color: const Color(0xFFFAFAFA),
        child: Stack(
          children: [
            image(
              'login/login_with_phone_bg.png',
              width: ScreenUtil().screenWidth,
              height: 184.h,
              fit: BoxFit.fitWidth,
            ),
            Scaffold(
              resizeToAvoidBottomInset: false,
              backgroundColor: Colors.transparent,
              appBar: CustomAppBar(
                titleBuilder: (c) => T.current.login_for_sms.text(
                  color: AppColors.COLOR_1B1B1B,
                  fontSize: 20,
                  weight: TextFontWeight.medium,
                ),
              ),
              body: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.all(16.w),
                    child: Container(
                      height: 36.h, // 增加高度
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(18.w),
                      ),
                      child: TextField(
                        controller: _searchController,
                        autofocus: false,
                        cursorColor: JR.color.cursorColor,
                        style: TextStyle(
                          color: const Color(0xFF948AAD),
                          fontSize: 15,
                          fontFamily: TextFontFamily.harmonyOS.family,
                          fontWeight: TextFontWeight.regular.toFontWeight,
                        ),
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(23),
                            borderSide: const BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                          prefixIcon: Container(
                            alignment: Alignment.center,
                            margin: EdgeInsets.zero,
                            // color: Colors.red,
                            width: 20.w,
                            height: 20.w,
                            child: JR.img(
                              'common/common_search_icon.png',
                              width: 20.w,
                              height: 20.w,
                            ),
                          ),
                          contentPadding: EdgeInsets.zero,
                          hintStyle: TextStyle(
                            color: const Color(0xFF948AAD),
                            fontSize: 15,
                            fontFamily: TextFontFamily.harmonyOS.family,
                            fontWeight: TextFontWeight.regular.toFontWeight,
                          ),
                          fillColor: Colors.transparent,
                          filled: true,
                          hintText: T.current.login_sms_phone,
                        ),
                      ),
                    ),
                  ),
                  Consumer<SelectCountryModel>(
                    builder: (context, model, _) {
                      final filteredList = _searchQuery.isEmpty
                          ? model.countryList
                          : model.countryList.where((country) {
                              final countryName =
                                  country.country?.toLowerCase() ?? '';
                              final countryCode =
                                  country.code?.toLowerCase() ?? '';
                              final query = _searchQuery.toLowerCase();
                              return countryName.contains(query) ||
                                  countryCode.contains(query);
                            }).toList();

                      return Expanded(
                        child: listWidget(context, model, filteredList),
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget listWidget(
      BuildContext context, SelectCountryModel model, List<CountryModel> list) {
    if (model.countryList.isEmpty) {
      return const SizedBox.shrink();
    }
    final double bottomHeight = 120.h;
    return Stack(
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 16, left: 14, right: 14),
          child: ListView.separated(
            itemCount: list.length + 1,
            // itemBuilder: (context, index) {
            //   final countryModel = list[index];
            //   final isSelected = index == model.selectedIndex;

            itemBuilder: (context, index) {
              // 添加边界判断
              if (index < list.length) {
                final countryModel = list[index];
                final isSelected = index == model.selectedIndex;

                return Container(
                  padding: const EdgeInsetsDirectional.all(12),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: isSelected ? Color(0xFFE5DFFF) : Colors.white,
                  ),
                  child: Row(
                    children: [
                      JR.img(
                        '${countryModel.flag}',
                        width: 32.w,
                        height: 22.w,
                        fit: BoxFit.fill,
                      ),
                      (countryModel.country ?? '')
                          .text(
                            color: AppColors.COLOR_1B1B1B,
                            fontSize: 14,
                          )
                          .padding(start: 11),
                      const Spacer(),
                      '+${countryModel.code}'
                          .text(
                            color: isSelected
                                ? AppColors.COLOR_8A72FE
                                : AppColors.COLOR_A8A8A8,
                            fontSize: 14,
                          )
                          .padding(end: 27),
                    ],
                  ),
                ).onTap(() {
                  model.setSelectedIndex(isSelected ? -1 : index);
                });
              } else {
                // 自定义视图

                return Container(
                  height: bottomHeight,
                  color: Colors.transparent,
                  // color: Colors.red,
                );
              }
            },
            separatorBuilder: (context, index) {
              // 最后两个元素之间不加分隔线（列表最后一项和自定义视图之间）
              return index < list.length - 1
                  ? const SizedBox(height: 15)
                  : const SizedBox.shrink();
            },
          ),
        ),
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          height: bottomHeight,
          child: bottomWidget(context),
        ),
      ],
    );
  }

  Widget bottomWidget(BuildContext context) {
    final model = Provider.of<SelectCountryModel>(context, listen: false);
    final isSelected = model.selectedIndex != -1;

    return Container(
      decoration: BoxDecoration(
        // border: Border.all(width: 1, color: Colors.red),
        gradient: LinearGradient(
          colors: [
            const Color(0xFFFFFFFF).withAlpha(0),
            const Color(0xFFFFFFFF).withAlpha(255),
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: isSelected
            ? () {
                final selectedCountry = model.countryList[model.selectedIndex];
                widget.onCountrySelected?.call(selectedCountry);
                Navigator.pop(context);
              }
            : null,
        child: Container(
          width: 248.w,
          height: 44.h,
          decoration: BoxDecoration(
            color:
                isSelected ? const Color(0xFF8A72FE) : const Color(0xFFE0DEEC),
            borderRadius: BorderRadius.circular(22.h),
          ),
          child: T.current.login_edit_sure
              .text(
                color: Colors.white,
                fontSize: 20,
                weight: TextFontWeight.medium,
              )
              .center(),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }
}
